import Start from "./Start";

// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class MainRankItem extends cc.Component {

    main: Start = null;

    @property(cc.Label)
    nick: cc.Label = null;

    @property(cc.Sprite)
    head: cc.Sprite = null;

    init(main: Start) {
        this.main = main
    }

    start () {

    } 

    reuse (main: Start) {
        this.init(main)
    }

    update (dt) {
        
        let point = cc.v2()
        if (this.main.mainCamera.getWorldToCameraPoint(this.node.convertToWorldSpaceAR(cc.v2(this.node.width/2.0,0)),point).x < 0) {
            this.main.despawnMainRankItem(this.node)
            console.log('-----')
        }
    }

    setData(obj) {
        if (obj.nickname || obj.nickName)
            this.nick.string = obj.nickName ? obj.nickName : obj.nickname
            
        let self = this
        if( cc.sys.platform == cc.sys.WECHAT_GAME && obj.avatarUrl){
            try {
                let image = wx.createImage();
                image.onload = () => {
                    try {
                        let texture = new cc.Texture2D();
                        texture.initWithElement(image);
                        texture.handleLoadedTexture();
                        self.head.spriteFrame = new cc.SpriteFrame(texture);
                    } catch (e) {
                        self.head.node.active = false;
                    }
                }
                image.src = obj.avatarUrl;
            }
            catch (e) {
                this.head.node.active = false;
            }
        }
    }
}
